import { getNumberValue, nilV } from "../common";

function parseDate(date: Date) {
    let weekDay = date.getDay();
    // 星期日是 0
    weekDay = weekDay === 0 ? 7 : weekDay;
    return {
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
        hour: date.getHours(),
        minute: date.getMinutes(),
        second: date.getSeconds(),
        weekDay,
    };
}

// 合成日期
function compositeDate(dateObj: {
    year: number;
    month: number;
    day: number;
    hour?: number;
    minute?: number;
    second?: number;
}): Date {
    let targetHour = dateObj.hour || 0;
    let targetMinute = dateObj.minute || 0;
    let targetSecond = dateObj.second || 0;
    return new Date(
        dateObj.year,
        dateObj.month - 1,
        dateObj.day,
        targetHour,
        targetMinute,
        targetSecond,
        0
    );
}

function number2Date(n: any): Date | null {
    let num = getNumberValue(n);
    if (nilV(num)) {
        return null;
    }
    let date = new Date(num!);
    if (date.toString() === "Invalid Date") {
        return null;
    }
    return date;
}

export { number2Date, parseDate, compositeDate };
